<template>
    <view class="cart-container">
        <!-- 顶部导航 -->
        <view class="header">
            <view class="back-btn" @click="goBack">
                <uni-icons type="left" size="24" color="#333"></uni-icons>
            </view>
            <text class="title">我的购物车</text>
            <view class="clear-btn" @click="showClearConfirm" v-if="shopGroups.length > 0">
                <text>清空</text>
            </view>
        </view>

        <!-- 购物车列表 -->
        <scroll-view scroll-y class="cart-scroll" v-if="shopGroups.length > 0">
            <!-- 店铺信息 -->
            <view class="shop-info" v-for="(shop, shopIndex) in shopGroups" :key="shop._id">
                <view class="shop-header" @click="goToShop(shop)">
                    <checkbox :checked="shop.selected" @click.stop="toggleShopSelect(shopIndex)" color="#0086ff" />
                    <image :src="getShopImage(shop._id)" mode="aspectFill"></image>
                    <text class="shop-name">{{shop.name}}</text>
                </view>

                <!-- 购物车列表 -->
                <view class="cart-list">
                    <view class="cart-item" v-for="(item, index) in shop.products" :key="item._id">
                        <view class="select-box">
                            <checkbox :checked="item.selected" @click="toggleProductSelect(shopIndex, index)" color="#0086ff" />
                        </view>
                        <image :src="item.imgUrl" mode="aspectFill"></image>
                        <view class="item-info">
                            <text class="item-name">{{item.name}} {{item.weight || ''}}</text>
                            <view class="item-sales">月售 {{item.sales || 10}} 件</view>
                            <view class="item-price-row">
                                <view class="price-container">
                                    <text class="price">¥{{item.price}}</text>
                                    <text class="old-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                                </view>
                                <view class="quantity-control">
                                    <text class="minus" @click="decreaseQuantity(shopIndex, index, item._id)">-</text>
                                    <text class="count">{{item.count}}</text>
                                    <text class="plus" @click="increaseQuantity(shopIndex, index, item._id)">+</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 店铺小计 -->
                <view class="shop-total">
                    <text class="total-text">总计: ¥ {{getShopTotal(shop).toFixed(2)}}</text>
                    <view class="checkout-btn" @click="checkoutShop(shopIndex)">
                        去结算
                    </view>
                </view>
            </view>
        </scroll-view>

        <!-- 空购物车提示 -->
        <view class="empty-cart" v-else>
            <uni-icons type="cart" size="60" color="#cccccc"></uni-icons>
            <text>购物车还是空的</text>
            <button class="go-shopping-btn" @click="goShopping">去购物</button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            cartProducts: {},
            cartList: [],
            shops: [],
            shopGroups: [],
            allSelected: true
        };
    },
    computed: {
        selectedCount() {
            let count = 0;
            this.shopGroups.forEach(shop => {
                shop.products.forEach(product => {
                    if (product.selected) {
                        count++;
                    }
                });
            });
            return count;
        },
        totalPrice() {
            let total = 0;
            this.shopGroups.forEach(shop => {
                shop.products.forEach(product => {
                    if (product.selected) {
                        total += product.price * product.count;
                    }
                });
            });
            return total;
        }
    },
    onLoad() {
        this.loadShops();
        this.loadCartData();
        uni.$on('cart-updated', this.handleCartUpdate);
    },
    onShow() {
        this.loadCartData();
    },
    onUnload() {
        uni.$off('cart-updated', this.handleCartUpdate);
    },
    methods: {
        getShopImage(shopId) {
            const shopImages = {
                '1': '/static/imgs/near.png',
                '2': '/static/imgs/yh.jpg'
            };
            return shopImages[shopId] || '/static/imgs/default-shop.png';
        },
        loadShops() {
            uni.request({
                url: 'http://localhost:3000/hotList',
                success: (res) => {
                    if (res.statusCode === 200) {
                        this.shops = res.data;
                    }
                }
            });
        },
        loadCartData() {
            const cartData = uni.getStorageSync('cartData');
            if (cartData) {
                this.cartProducts = JSON.parse(cartData);
                uni.request({
                    url: 'http://localhost:3000/products-all',
                    success: (res) => {
                        if (res.statusCode === 200) {
                            this.processCartData(res.data);
                        }
                    }
                });
            } else {
                this.cartList = [];
                this.shopGroups = [];
            }
        },
        processCartData(allProducts) {
            this.cartList = [];
            
            // 创建商品映射
            const productMap = {};
            allProducts.forEach(product => {
                productMap[product._id] = product;
            });
            
            // 处理购物车数据
            for (const productId in this.cartProducts) {
                const product = productMap[productId];
                if (product) {
                    this.cartList.push({
                        ...product,
                        count: this.cartProducts[productId],
                        selected: true
                    });
                }
            }
            
            this.groupProductsByShop();
        },
        groupProductsByShop() {
            const shopMap = {};
            
            // 初始化已知店铺
            this.shops.forEach(shop => {
                shopMap[shop._id] = {
                    ...shop,
                    products: [],
                    selected: true
                };
            });
            
            // 分配商品到店铺
            this.cartList.forEach(item => {
                const shopId = item.shopId;
                if (!shopMap[shopId]) {
                    shopMap[shopId] = {
                        _id: shopId,
                        name: item.shopName || '未知店铺',
                        imgUrl: this.getShopImage(shopId),
                        products: [],
                        selected: true
                    };
                }
                shopMap[shopId].products.push(item);
            });
            
            this.shopGroups = Object.values(shopMap).filter(shop => shop.products.length > 0);
        },
        toggleShopSelect(shopIndex) {
            const shop = this.shopGroups[shopIndex];
            shop.selected = !shop.selected;
            shop.products.forEach(product => {
                product.selected = shop.selected;
            });
        },
        toggleProductSelect(shopIndex, productIndex) {
            const product = this.shopGroups[shopIndex].products[productIndex];
            product.selected = !product.selected;
            
            // 更新店铺选中状态
            const shop = this.shopGroups[shopIndex];
            shop.selected = shop.products.every(p => p.selected);
        },
        increaseQuantity(shopIndex, productIndex, productId) {
            const product = this.shopGroups[shopIndex].products[productIndex];
            product.count++;
            this.updateCart(productId, product.count);
        },
        decreaseQuantity(shopIndex, productIndex, productId) {
            const product = this.shopGroups[shopIndex].products[productIndex];
            if (product.count > 1) {
                product.count--;
                this.updateCart(productId, product.count);
            } else {
                uni.showModal({
                    title: '提示',
                    content: '确定要移除该商品吗？',
                    success: (res) => {
                        if (res.confirm) {
                            this.removeProduct(shopIndex, productIndex, productId);
                        }
                    }
                });
            }
        },
        updateCart(productId, count) {
            // 更新全局购物车
            this.cartProducts[productId] = count;
            uni.setStorageSync('cartData', JSON.stringify(this.cartProducts));
            
            // 触发更新事件
            uni.$emit('cart-updated', {
                productId: productId,
                count: count
            });
        },
        removeProduct(shopIndex, productIndex, productId) {
            // 从界面移除
            this.shopGroups[shopIndex].products.splice(productIndex, 1);
            
            // 如果店铺没有商品了，移除店铺
            if (this.shopGroups[shopIndex].products.length === 0) {
                this.shopGroups.splice(shopIndex, 1);
            }
            
            // 更新全局购物车
            delete this.cartProducts[productId];
            uni.setStorageSync('cartData', JSON.stringify(this.cartProducts));
            
            // 触发更新事件
            uni.$emit('cart-updated', {
                productId: productId,
                count: 0
            });
        },
        getShopTotal(shop) {
            return shop.products
                .filter(p => p.selected)
                .reduce((total, product) => total + product.price * product.count, 0);
        },
     // 购物车页面中的方法
checkoutShop(shopIndex) {
  const shop = this.shopGroups[shopIndex];
  const selectedProducts = shop.products.filter(p => p.selected);
  
  if (selectedProducts.length === 0) {
    uni.showToast({
      title: '请选择要结算的商品',
      icon: 'none'
    });
    return;
  }
  
  // 准备结算数据
  const checkoutData = {
    shop: {
      _id: shop._id,
      name: shop.name,
      imgUrl: shop.imgUrl,
      expressLimit: shop.expressLimit,
      expressPrice: shop.expressPrice
    },
    products: selectedProducts.map(p => ({
      ...p,
      shopName: shop.name
    }))
  };
  
  // 保存店铺信息到本地存储
  uni.setStorageSync('shopInfo', JSON.stringify(checkoutData.shop));
  
  // 保存购物车数据到本地存储
  const cartData = {};
  selectedProducts.forEach(product => {
    cartData[product._id] = product.count;
  });
  uni.setStorageSync('cartData', JSON.stringify(cartData));
  
  // 跳转到确认订单页面
  uni.navigateTo({
    url: '/pages/order/order-confirm'
  });
},
        showClearConfirm() {
            uni.showModal({
                title: '提示',
                content: '确定要清空购物车吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.clearCart();
                    }
                }
            });
        },
        clearCart() {
            this.cartProducts = {};
            this.shopGroups = [];
            uni.removeStorageSync('cartData');
            uni.$emit('cart-cleared');
        },
        handleCartUpdate(data) {
            const { productId, count } = data;
            
            // 查找商品是否已在购物车中
            let found = false;
            for (let i = 0; i < this.shopGroups.length; i++) {
                const shop = this.shopGroups[i];
                const productIndex = shop.products.findIndex(p => p._id === productId);
                
                if (productIndex >= 0) {
                    found = true;
                    if (count > 0) {
                        shop.products[productIndex].count = count;
                    } else {
                        shop.products.splice(productIndex, 1);
                        if (shop.products.length === 0) {
                            this.shopGroups.splice(i, 1);
                        }
                    }
                    break;
                }
            }
            
            // 如果商品不在购物车中且被添加了，重新加载数据
            if (!found && count > 0) {
                this.loadCartData();
            }
        },
        goShopping() {
            uni.switchTab({
                url: '/pages/homepage/index'
            });
        },
        goBack() {
            uni.navigateBack();
        },
        goToShop(shop) {
            uni.navigateTo({
                url: `/pages/shop/shop?id=${shop._id}&name=${encodeURIComponent(shop.name)}`
            });
        }
    }
};
</script>

<style lang="scss">
.cart-container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 100rpx;
}

.header {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background-color: #fff;

    .back-btn {
        width: 60rpx;
    }

    .title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: bold;
    }

    .clear-btn {
        width: 60rpx;
        font-size: 26rpx;
        color: #666;
    }
}

.cart-scroll {
    height: calc(100vh - 180rpx);
}

.shop-info {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 12rpx;
    overflow: hidden;

    .shop-header {
        display: flex;
        align-items: center;
        padding: 20rpx;
        border-bottom: 1rpx solid #f5f5f5;

        image {
            width: 40rpx;
            height: 40rpx;
            border-radius: 8rpx;
            margin: 0 20rpx;
        }

        .shop-name {
            font-size: 28rpx;
            font-weight: bold;
        }
    }
}

.cart-list {
    .cart-item {
        display: flex;
        padding: 20rpx;
        border-bottom: 1rpx solid #f5f5f5;

        .select-box {
            display: flex;
            align-items: center;
            margin-right: 20rpx;
        }

        image {
            width: 140rpx;
            height: 140rpx;
            border-radius: 8rpx;
            margin-right: 20rpx;
        }

        .item-info {
            flex: 1;
            position: relative;

            .item-name {
                font-size: 28rpx;
                margin-bottom: 10rpx;
            }

            .item-sales {
                font-size: 24rpx;
                color: #999;
                margin-bottom: 30rpx;
            }

            .item-price-row {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .price-container {
                    .price {
                        font-size: 32rpx;
                        color: #ff6b6b;
                        font-weight: bold;
                    }

                    .old-price {
                        font-size: 24rpx;
                        color: #999;
                        text-decoration: line-through;
                        margin-left: 10rpx;
                    }
                }

                .quantity-control {
                    display: flex;
                    align-items: center;

                    .minus,
                    .plus {
                        width: 50rpx;
                        height: 50rpx;
                        line-height: 46rpx;
                        text-align: center;
                        border-radius: 50%;
                        border: 1rpx solid #eee;
                        font-size: 28rpx;
                    }

                    .count {
                        margin: 0 20rpx;
                        font-size: 28rpx;
                    }

                    .plus {
                        background-color: #0086ff;
                        color: #fff;
                        border: none;
                    }
                }
            }
        }
    }
}

.shop-total {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20rpx;
    border-top: 1rpx solid #f5f5f5;

    .total-text {
        font-size: 28rpx;
        margin-right: 20rpx;
    }

    .checkout-btn {
        background-color: #0086ff;
        color: #fff;
        padding: 10rpx 30rpx;
        border-radius: 30rpx;
        font-size: 28rpx;
    }
}

.empty-cart {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;

    text {
        font-size: 28rpx;
        color: #999;
        margin-bottom: 30rpx;
    }

    .go-shopping-btn {
        background-color: #0086ff;
        color: #fff;
        font-size: 28rpx;
        padding: 10rpx 40rpx;
        border-radius: 30rpx;
    }
}
</style>    